package sicnu.cs.ich.token.security.aop;

import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import sicnu.cs.ich.token.security.util.SecurityUtil;

import java.util.Set;

/**
 * @author CaiKe
 * @date 2021/12/26 17:14
 */
@Component
@Aspect
@RequiredArgsConstructor
public class TokenAOP {

    private final SecurityUtil securityUtil;


    @Pointcut("@annotation(sicnu.cs.ich.token.security.aop.HasAuth)")
    public void pointCut() {
    }

    @Before(value = "pointCut()")
    public void preCheckAuth(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取注解
        final HasAuth anno = signature.getMethod().getAnnotation(HasAuth.class);
        boolean hasAuth = false;
        if (anno != null) {
            // 判断用户是否拥有注解中的权限
            final Set<String> currentUserAuth = securityUtil.getCurrentUserAuth();
            if (currentUserAuth != null) {
                for (String auth : anno.value()) {
                    if (currentUserAuth.contains(auth)) {
                        hasAuth = true;
                        break;
                    }
                }
            }
        }
        if (!hasAuth) {
            throw new HttpClientErrorException(HttpStatus.FORBIDDEN);
        }

    }

}